package com.rockcent.mall.lib.helper;

import com.rockcent.common.BaseConfig;
import com.rockcent.common.BaseProp;
import com.rockcent.common.utils.BaseCommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by oyhk on 16/7/19.
 */
@Component
public class BaseCaptchaHelper {

    private final Logger log = LoggerFactory.getLogger(BaseCaptchaHelper.class);

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private BaseSMSHelper smsHelper;
    @Autowired
    private ExecutorService commonExecutorService;
    @Autowired
    private BaseProp prop;

    /**
     * 发送短信
     *
     * @param mobile   手机号码
     * @param key      redis key
     * @param timeLeft 有效时间
     * @return
     */
    public String send(String mobile, String mallName, String key, int timeLeft) {
        Object oCaptcha = redisTemplate.opsForValue().get(key);
        if (oCaptcha != null) {
            return String.valueOf(oCaptcha);
        }
        String captchaTemp = BaseCommonUtils.getRandom6();
        redisTemplate.boundValueOps(key).set(captchaTemp);
        redisTemplate.expire(key, timeLeft, TimeUnit.SECONDS);
        //生产环境 或者 UAT 才会调用短信接口
        log.info("======================>msg send start");
        if (prop.env.equals(BaseConfig.UAT) || prop.env.equals(BaseConfig.PROD)) {
            log.info("======================>msg send env : {}", prop.env);
            commonExecutorService.execute(() -> {
                if (mallName != null) {
                    smsHelper.send(mobile, String.valueOf(captchaTemp), mallName);
                } else {
                    smsHelper.send(mobile, captchaTemp);
                }

            });
            return null;
        }
        log.info("======================>msg send end");
        return captchaTemp;
    }
}
